<?php

namespace app\api\logic\lawyer;

use app\common\logic\BaseLogic;
use app\common\logic\common\CommonLogic;
use app\common\model\Category;
use app\common\model\Goods;
use app\common\model\lawyer\CategorySon;
use app\common\model\Order;

class SingleOrderLogic extends BaseLogic
{
    public function add($data)
    {
        $goods = Goods::find($data['goods_id']);
        if (!$goods) throwError('商品不存在');
        if ($goods->stock <= 0) throwError('库存不足');
        $exit = Order::where("user_id",$data['user_id'])
            ->where('type','buy')
            ->where("status","<>",-1)
            ->find();
        if ($exit) throwError('您已经购买过了');

        $order = new Order();
        $order->order_no = CommonLogic::makeOrderNo();
        $order->goods_id = $goods->id;
        $order->money = $goods->price;
        $order->user_id = $data['user_id'];
        $order->info = [
            "create_time" => date("Y-m-d H:i")
        ];
//        $categorySon = CategorySon::where("id",$goods->category_son_id)->find();
//        $category = Category::find($goods->category_id);
        $order->body = [
            'goods' => $goods->toArray(),
//            'category' => $category,
//            'categorySon' => $categorySon
        ];
        $order->save();
        return $order;
    }
}